package utils.socket;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

import javax.swing.Timer;

import modelo.mensajes.Mensaje;

public class ClientKeepAliveSocket {
	
	private static final long serialVersionUID = 1L;
	private Socket sock;
	private boolean ka_on = false;
	private ISocketListener sl = null;
	private Timer timer = null;
	
	// Para la transmision de datos
	private DataInputStream in;
	private DataOutputStream out;
	
	// El emmarcador
	private Enmarcador marker;
	
	// Leer de la configuracion
	// private int id_cap = 1;
	// Necesito un generador de nros 
	// private int id_msj = 1;	
	
	public ClientKeepAliveSocket(Socket s){
		sock = s;
		try {
			in      = new DataInputStream(sock.getInputStream());
			out     = new DataOutputStream(sock.getOutputStream());
			marker  = new Enmarcador(in, out);
			
			// 60 seg de timer
			timer  = new Timer(0, null);
			timer.setRepeats(false);
		} catch (IOException e) { e.printStackTrace(); }		
	}
	
	public void setKeepAlive(boolean ka){
		ka_on = ka;
		if(ka) { // ka == false
			timer.start();
		} else {
			timer.stop();
		}
	}
	
	public boolean getKeepAlive(){
		return ka_on;
	}
	
	private void desconectar(){
		try {
			in.close();
			out.close();
			sock.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public synchronized void send(Mensaje m) throws IOException{
		byte[] msj_byte = m.toByte(); 
		// marker.enmarcar(msj_byte, gzipout);
		marker.enmarcar(msj_byte);
	}
	
	public void addListener(ISocketListener sl){
		this.sl = sl;
	}

	private String getTipo(byte[] input) throws IOException{
		String ret = null;
		ByteArrayInputStream bais = new ByteArrayInputStream(input);
		DataInputStream in  = new DataInputStream(bais);
		in.readUTF();
		ret = in.readUTF(); 		
		in.close();
		bais.close();
		
		return ret;
	}
	
}

